package com.linsy.product.redis.mq.config;

import cn.hutool.core.text.CharSequenceUtil;
import com.linsy.product.redis.mq.annotation.EnableKernelMq;
import com.linsy.product.redis.mq.service.ConsumersMsgDecorator;
import com.linsy.product.redis.mq.util.ClassScanner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * 扫描MQ类
 */
@Slf4j
public class KernelMqRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes mapperScanAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableKernelMq.class.getName()));
        if (mapperScanAttrs != null) {
            // 包扫描
            String basePackages = mapperScanAttrs.getString("basePackages");
            if (CharSequenceUtil.isBlank(basePackages)) {
                log.error("请配置包扫描地址！");
                return;
            }
            // 定时任务配置
            String cron = mapperScanAttrs.getString("cron");
            if (CharSequenceUtil.isBlank(cron)) {
                log.error("请配置定时任务cron！");
                return;
            }

            ClassScanner classScanner = new ClassScanner();
            KernelMqDataConfig.classSet = classScanner.scan(basePackages);
            KernelMqDataConfig.cron = cron;
            KernelMqDataConfig.classSet.removeIf(aClass -> !ConsumersMsgDecorator.class.isAssignableFrom(aClass));
            log.debug("扫描到的MQ类：" +  KernelMqDataConfig.classSet);
            log.debug("MQ定时任务cron：" +  cron);
            classScanner = null;
        }

        ImportBeanDefinitionRegistrar.super.registerBeanDefinitions(importingClassMetadata, registry);
    }

}
